<?php

/**
 *  Component: JUser - Extends Jomla registration
 *  Author: http://joomlaequipment.com
 *  license: commercial http://joomlaequipment.com/content/view/10/42/
 *  version: 1.0.6
 */

// no direct access
error_reporting(E_ALL ^ E_NOTICE);
//error_reporting(E_ALL);
defined( '_VALID_MOS' ) or die( 'Restricted access' );

if(file_exists($mosConfig_absolute_path ."/administrator/components/com_juser/language/{$mosConfig_lang}.php")){
	include_once( $mosConfig_absolute_path ."/administrator/components/com_juser/language/{$mosConfig_lang}.php" );
}
else{
	include_once( $mosConfig_absolute_path ."/administrator/components/com_juser/language/english.php" );
}

if(file_exists($mosConfig_absolute_path ."/administrator/components/com_juser/additional_data.php"))
	include_once($mosConfig_absolute_path ."/administrator/components/com_juser/additional_data.php");

require_once($mosConfig_absolute_path.'/administrator/components/com_installer/installer.class.php');

require_once ( $mainframe->getPath( 'front_html' ) );
require_once( $mosConfig_absolute_path .'/administrator/components/com_juser/juser.class.php' );
if(!class_exists('JEConfig')){
	require_once( $mosConfig_absolute_path .'/administrator/components/com_juser/joomlaequipment.config.php' );
}

require_once( $mosConfig_absolute_path."/includes/domit/xml_domit_lite_parser.php" );

$limit 		= intval( mosGetParam( $_REQUEST, 'limit', '' ) );
$limitstart = intval( mosGetParam( $_REQUEST, 'limitstart', 0 ) );

switch( $task ) {
  case 'pc':
    $captcha_text = RandString(JEConfig::get('general.count_chars_captcha'),JEConfig::get('general.captcha_character_set'));
    print'Antispam picture: <img src="index.php?option=com_juser&task=captcha&tapochka='.base64_encode($captcha_text).'">';
    break;

  case 'captcha':
    require_once $mosConfig_absolute_path .'/administrator/components/com_juser/lib/jpgraph_antispam.php';
    $spam = new AntiSpam();
    //$chars = $spam->Rand(5);
    $spam->iData = base64_decode(mosGetParam($_REQUEST,'tapochka','' ));
    if( $spam->Stroke() === false ) die('Illegal or no data to plot');
    $_SESSION['capcha'] = $spam->iData;
    exit;
    break;
  case 'remove_myself':
    removeMyself();
    break;
  case 'blank_page':
    break;
  case 'show_profile':
    if (isset($my) && $my->id != 0) $user_register = 1;
    else $user_register=0;
    $id=mosGetParam($_REQUEST, 'id', 0 );
    $query = "SELECT *"
            ."\n FROM #__users"
            ."\n WHERE `id`= ".$id." AND `block` = 0";
    $database->setQuery( $query );
    $user = $database->loadObjectList();
    $query = "SELECT fl.* , ud.field_id,ud.user_id,ud.uvalue,ud.ctime, fl.id as field_id, #__categories.title as cat_title"
         		. "\n FROM #__extending_field_list as `fl`"
         		. "\n LEFT JOIN #__users_extended_data as `ud` ON fl.id = ud.field_id"
         		. "\n AND ud.user_id = ".$id
         		. "\n LEFT JOIN #__categories ON #__categories.id = fl.catid"
            . "\n WHERE fl.`published` = 1 AND  fl.`display_at_users_list` IN ( 1, 0 ) AND  fl.`access` <= ".$user_register
         		. "\n ORDER by #__categories.ordering, fl.ordering";
    $database->setQuery( $query );
    $ext_fields = $database->loadObjectList();
    HTML_JUser::show_user_profile($user[0],$ext_fields);
    break;
  case 'user_list':
    if( JEConfig::get('general.show_users_list') == 0){break;}
     userList();
    break;
	case 'UserRegistration':
	  if (!$mainframe->getCfg( 'allowUserRegistration' )) {
  		mosNotAuth();
  	}
		else if($my->id){
      //$mainframe->logout();
      print JUSER_ALREADY_REGISTER;
			//mosRedirect( 'index.php?option=com_juser&task=UserRegistration' );
		}
    else{
		  userRegistration( $option, $my->id);
    }
		break;
	case 'saveUserRegistration':
		if(mosGetParam( $_POST, 'tc', '' )!='agree' && JEConfig::get('general.registraton_policy'))
		{
			userRegistrationAfterError( "com_juser", $my->id, array(), HEAD_MSG_IF_DONT_AGREE, $task );
		}
		else if(base64_decode(mosGetParam( $_POST, 'hidden_captcha', '' )) != strtolower(mosGetParam( $_POST, 'captcha_validate', '' )) && JEConfig::get('general.captcha_on'))
		{
			userRegistrationAfterError( "com_juser", $my->id, array(), HEAD_MSG_CAPTCHA_WRONG, $task );
		}
		else if(JUser::validateSaveUser('','front','saveUserRegistration'))
		{
			if(saveRegistration($task)){
				$query = "SELECT * FROM #__users where `username`='".mosGetParam($_POST, 'username')."' and `email`='".mosGetParam($_POST, 'email')."'";
				$database->setQuery( $query );
				$current_user = $database->loadObjectList();
				JUser::saveUser_ext($current_user[0]->id);
				//synchronize dublicate user data
    		  $database->setQuery("SELECT `id` FROM  `#__juser_integration` WHERE  `published` = 1 AND `export_status` = 1");
    		  $components = $database->loadObjectList();
    		  foreach($components as $component)
    		  {
      		  /*$xml = new integration_XML ($component->id);
            $synchronize = new synchronizeUsersData($xml);
            $synchronize->synchronizeFrom($current_user[0]);*/
      		  $synchronize = require_integration($component->id);
      		  //$synchronize = new comIntegration ( $component->id );
      		  $synchronize->synchronizeFrom( $current_user[0]->id );
    		  }
        //synchronize dublicate user data(end)
			if(JEConfig::get('general.content_after_registration')){
        mosRedirect( 'index.php?option=com_content&task=view&id='.JEConfig::get('general.content_after_registration') );
				}
			}
		}
		break;
	case 'UserDetails':
		userEdit( $option, $my->id, _UPDATE);
		break;
	case 'saveUserEdit':
		// check to see if functionality restricted for use as demo site
		if ( $_VERSION->RESTRICT == 1 ) {
			mosRedirect( 'index.php?mosmsg=Functionality is restricted' );
		} else {
			if(JUser::validateSaveUser('','front','saveUserEdit'))
			{
				userSave( $option, $my->id, $task );
  	  //synchronize dublicate user data
  		  $database->setQuery("SELECT `id` FROM  `#__juser_integration` WHERE  published` = 1 AND `export_status` = 1");
  		  $components = $database->loadObjectList();
  		  foreach($components as $component)
  		  {
    		  $synchronize = require_integration($component->id);
          //$synchronize = new comIntegration ( $component->id );
      		$synchronize->synchronizeFrom( $my->id );
  		  }
  		//synchronize dublicate user data(end)
  		  mosRedirect( 'index.php?option=com_juser&task=UserDetails', _USER_DETAILS_SAVE );
		  }
		}
		break;

	case 'CheckIn':
		CheckIn( $my->id, $access, $option );
		break;

	default:
		HTML_JUser::frontpage();
		break;
}
function removeMyself(){
  global $database, $my, $mainframe;
  if(!$my->id) mosRedirect( 'index.php?mosmsg=You are not loggined' );
	$obj = new mosUser( $database );
	$obj->load( $my->id );
	$obj->delete( $my->id );

	$query = "DELETE FROM #__users_extended_data"
				. "\n WHERE `user_id` = ".$my->id;
		$database->setQuery( $query );
	$database->query();

	$msg = $obj->getError();

	$mainframe->logout();
	//synchronize dublicate delete
	  $database->setQuery("SELECT `id` FROM  `#__juser_integration` WHERE  published` = 1 AND `export_status` = 1");
	  $components = $database->loadObjectList();
	  if(count($components)>0){
  	  foreach($components as $component)
  	  {
  		  $synchronize = require_integration($component->id);
  		  //$synchronize = new comIntegration ( $component->id );
        $synchronize->deleteExteriorUser( $my->id );
  	  }
	  }
  //synchronize dublicate delete(end)
  return $msg;
  mosRedirect( 'index.php?mosmsg=Youre profile is deleted' );
}
function userList()
{
?>
<script type="text/javascript" src="<?php echo $mosConfig_live_site;?>includes/js/joomla.javascript.js"></script>
<?php 
  global $mainframe, $database, $my, $mosConfig_absolute_path;
  mosCommonHTML::loadCalendar();

  $filter_type =  mosGetParam($_REQUEST,'filter_type','');
  $filter_logged=  mosGetParam($_REQUEST,'filter_logged',0);

  // get list of Groups for dropdown filter
	$query = "SELECT group_id AS value, name AS text"
	. "\n FROM #__core_acl_aro_groups"
	. "\n WHERE name != 'ROOT'"
	. "\n AND name != 'USERS'"
	;

	$types[] = mosHTML::makeOption( '0', '- Select Group -' );
	$database->setQuery( $query );
	$types = array_merge( $types, $database->loadObjectList() );
	$lists['type'] = mosHTML::selectList( $types, 'filter_type', 'class="inputbox" size="1" onchange="document.mosUserForm.submit( );"', 'value', 'text', $filter_type );

	// get list of Log Status for dropdown filter
	$logged[] = mosHTML::makeOption( 0, '- Select Log Status - ');
	$logged[] = mosHTML::makeOption( 1, 'Logged In');
	$lists['logged'] = mosHTML::selectList( $logged, 'filter_logged', 'class="inputbox" size="1" onchange="document.mosUserForm.submit( );"', 'value', 'text', $filter_logged );
	// get list of Log Status for dropdown filter

	$database->setQuery("SELECT * FROM `#__extending_field_list` WHERE `search_by_this_field` = 1 AND `published` = 1");
  $fields_for_filter = $database->loadObjectList();
  foreach($fields_for_filter as $field){
    if($field->type == 'select' || $field->type == 'radio' || $field->type == 'checkbox'){
      unset($temp_list);
      $temp_list[] = mosHTML::makeOption( '', '- Select '.str_limit($field->title,30).' - ');

      $values_for_filter = explode("\n",str_replace("\r", "", $field->uvalues));
      foreach($values_for_filter as $value){
        $temp_list[] = mosHTML::makeOption( $value, str_limit($value,30));
      }
      $lists['additional_filters'][] = mosHTML::selectList( $temp_list, $field->id.'filter_field', 'class="inputbox" size="1" onchange="document.mosUserForm.submit( );"', 'value', 'text', mosGetParam($_REQUEST, $field->id.'filter_field') );
    } else if ( $field->type == 'date' ) {
	  
	  $filter_value	= mosGetParam($_REQUEST, $field->id.'filter_field', '' );
	  $filter_sign	= mosGetParam($_REQUEST, $field->id.'filter_field_sign', '' );
	  
	  unset($temp_list);
	  
	  $temp_list[] = mosHTML::makeOption( '1', FILTERS_EQUIVALENT );
	  $temp_list[] = mosHTML::makeOption( '2', FILTERS_MORE );
	  $temp_list[] = mosHTML::makeOption( '3', FILTERS_LESS );
	  $temp_list[] = mosHTML::makeOption( '4', FILTERS_MORE_EQUIVALENT );
	  $temp_list[] = mosHTML::makeOption( '5', FILTERS_LESS_EQUIVALENT );

	  $date_filter  = ' '.str_limit($field->title,30).' : ';
	  $date_filter .= mosHTML::selectList( $temp_list, $field->id.'filter_field_sign', ' class="inputbox" ', 'value', 'text', $filter_sign );
	  $date_filter .= '<input type="text" name = "'.$field->id.'filter_field'.'" id="'.$field->id.'filter_field" value="'.$filter_value.'">';
	  $date_filter .= "<input name=\"reset\" type=\"reset\" class=\"button\" onclick=\"return showCalendar('".$field->id."filter_field', 'y-mm-dd');\" value=\"...\" />";
	  $date_filter .= '<input name="submit" type="submit" class="button" value="search" />';
	  
	  $lists['additional_filters'][] = $date_filter;
	}
  }


  $query = "SELECT COUNT(`id`)"
        ."\n FROM #__users"
        ."\n WHERE `block` = 0".$search;
  $database->setQuery( queryWithFlters('',true) );
  $total = $database->loadResult();
  $limit = mosGetParam($_REQUEST,'limit','');
  $limitstart = mosGetParam($_REQUEST,'limitstart','');
  $limit = $limit ? $limit : JEConfig::get('general.count_cards') ;
  if ( $total <= $limit ) $limitstart = 0;
  $query = "SELECT *"
        ."\n FROM #__users"
        ."\n WHERE `block` = 0".$search
        ."\n LIMIT ".$limitstart.",".$limit;
  $database->setQuery( queryWithFlters(), $limitstart, $limit);
  $users = $database->loadObjectList();
  require_once( $mosConfig_absolute_path.'/includes/pageNavigation.php' );
  $pageNav = new mosPageNav( $total, $limitstart, $limit );

  HTML_JUser::show_user_list($users, $lists, $pageNav );
}

function userRegistrationAfterError($option, $uid,$ext_rows ,$msg,$task)
{
	global $database, $mainframe;
	global $mosConfig_absolute_path;
	require_once( $mosConfig_absolute_path .'/administrator/components/com_juser/juser.class.php' );

	$row = new mosUser( $database );
	$row->load( (int)$uid );
	$row->orig_password = $row->password;



	$file 	= $mainframe->getPath( 'com_xml', 'com_users' );
	$params =& new mosUserParameters( $row->params, $file, 'component' );
	if(count($ext_rows)==0)
	{
		$query = "SELECT #__extending_field_list. *, #__extending_field_list.id as field_id, #__categories.title as cat_title, #__categories.description as cat_description"
			. "\n FROM #__extending_field_list"
			. "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
			. "\n ORDER by #__categories.ordering, #__extending_field_list.ordering";
			//print'haflhsdlfhnas';exit;
		$database->setQuery( $query );
		$ext_rows = $database->loadObjectList();
    @$ext_rows->coreavatar = mosGetParam($_POST, 'field_core_avatar', '');
		for($i=0;$i<count($ext_rows);$i++)
		{
			switch($ext_rows[$i]->type)
			{
				case 'select':
				case 'radio':
				case 'text':
				case 'textarea':
					$value=mosGetParam($_POST, 'extend'.$ext_rows[$i]->id);
					break;
				case 'checkbox':
					$value=mosGetParam($_POST, 'extend'.$ext_rows[$i]->id,'','array');
					$value=is_array($value)?implode("\r\n", $value) : $value='';
					break;
				case 'date':
					$data['d']=mosGetParam($_POST, 'extend_d'.$ext_rows[$i]->id);
          $data['m']=mosGetParam($_POST, 'extend_m'.$ext_rows[$i]->id);
          $data['y']=mosGetParam($_POST, 'extend_y'.$ext_rows[$i]->id);
					if(!$data['y'] || !$data['m'] || !$data['d']){
						$value='';
					}
					else{
						$value=is_array($data)?implode("-", $data) : $value='';
					}
					break;
				case 'file':
          $ufile=$_FILES['extend'.$field->id];
					$value=$ufile['name'];
					break;
        case 'phone':
          $phone['code']= mosGetParam($_POST, 'extend_code'.$field->id);
      		$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
      		$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
      		$phone['extention']=mosGetParam($_POST, 'extend_extention'.$field->id);
      		if(!$phone['code'] || !$phone['prefix'] || !$phone['phone']){
      			$value='';
      		}else{
      			$value=serialize($phone);
      		}
          break;
        case 'simple phone':
      		$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
      		$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
      		if(!$phone['prefix'] || !$phone['phone']){
      			$value='';
      		}else{
      			$value=serialize($phone);
      		}
          break;
			}
			$ext_rows[$i]->uvalue=$value;
		}
	}

	if( mosGetParam($_POST, 'password') != mosGetParam($_POST, 'verifyPass')){ $row->passworderror=HEAD_MSG_IF_PASSWORDS_ISNOT_SAME; }
	if( !preg_match("/[0-9a-z_]+@[0-9a-z_^\.\-]+\.[a-z]{2,3}/i", mosGetParam($_POST, 'email'))){ $row->emailerror=MSG_IF_FIELD_IS_NOT_VALID; }
	if( !mosGetParam($_POST, 'name') ){ $row->nameerror=MSG_IF_FIELD_IS_EMPTY; }
	if( !mosGetParam($_POST, 'email') ){ $row->emailerror=MSG_IF_FIELD_IS_EMPTY; }
	if( !mosGetParam($_POST, 'username') ){ $row->usernameerror=MSG_IF_FIELD_IS_EMPTY; }
	if( !mosGetParam($_POST, 'password') && $task != 'saveUserEdit'){ $row->passworderror=MSG_IF_FIELD_IS_EMPTY; }
	if( !mosGetParam($_POST, 'verifyPass') && $task != 'saveUserEdit' ){ $row->verifyPasserror=MSG_IF_FIELD_IS_EMPTY; }

	$row->id=mosGetParam($_POST, 'id');
	$row->name=mosGetParam($_POST, 'name');
	$row->email=mosGetParam($_POST, 'email');
	$row->username=mosGetParam($_POST, 'username');

	HTML_JUser::userEdit( $row, $option, $params, $ext_rows, $task,$msg);
}

function userRegistration($option, $uid)
{
	global $database, $mainframe;
	global $mosConfig_absolute_path;
	require_once( $mosConfig_absolute_path .'/administrator/components/com_juser/juser.class.php' );

	$row = new mosUser( $database );
	$row->load( (int)$uid );
	$row->orig_password = $row->password;

	$file 	= $mainframe->getPath( 'com_xml', 'com_users' );
	$params =& new mosUserParameters( $row->params, $file, 'component' );

	$query = "SELECT #__extending_field_list. *, #__extending_field_list.id as field_id, #__categories.title as cat_title, #__categories.description as cat_description"
		. "\n FROM #__extending_field_list"
		. "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
		. "\n ORDER by #__categories.ordering, #__extending_field_list.ordering";
	$database->setQuery( $query );
	$ext_row = $database->loadObjectList();
	HTML_JUser::userEdit( $row, $option, $params, $ext_row, 'saveUserRegistration' );
}

function saveRegistration($task) {
	global $database, $acl,$my;
	global $mosConfig_sitename, $mosConfig_live_site, $mosConfig_useractivation, $mosConfig_allowUserRegistration;
	global $mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_mailfrom, $mosConfig_fromname;



	// simple spoof check security
	//josSpoofCheck();

	$row = new mosUser( $database );

	if (!$row->bind( $_POST, 'usertype' )) {
		mosErrorAlert( $row->getError() );
	}

	mosMakeHtmlSafe($row);

	$row->id = 0;
	$row->usertype = '';
	$row->gid = $acl->get_group_id( 'Registered', 'ARO' );

	if ( $mosConfig_useractivation == 1 ) {
		$row->activation = md5( mosMakePassword() );
		$row->block = '1';
	}

	if (!$row->check()) {

		userRegistrationAfterError("com_juser", $my->id,array(), $row->getError(), $task);
		return false;
	}

	$pwd 				= $row->password;
	$row->password 		= md5( $row->password );
	$row->registerDate 	= date('Y-m-d H:i:s');

	if (!$row->store()) {
		userRegistrationAfterError("com_juser", $my->id, array(), $row->getError(), $task);
		return false;
	}
	$row->checkin();

	$name 		= $row->name;
	$email 		= $row->email;
	$username 	= $row->username;

	$subject 	= sprintf (_SEND_SUB, $name, $mosConfig_sitename);
	$subject 	= html_entity_decode($subject, ENT_QUOTES);

	if(JEConfig::get('general.activationuser_manual')){
	  $message = sprintf (JUSER_USEND_MSG, $name, $mosConfig_sitename, $mosConfig_live_site, $username, $pwd);
	}
	else{
  	if ($mosConfig_useractivation == 1){
  		$message = sprintf (_USEND_MSG_ACTIVATE, $name, $mosConfig_sitename, $mosConfig_live_site."/index.php?option=com_registration&task=activate&activation=".$row->activation, $mosConfig_live_site, $username, $pwd);
  	} else {
  		$message = sprintf (_USEND_MSG, $name, $mosConfig_sitename, $mosConfig_live_site);
  	}
	}

	$message = html_entity_decode($message, ENT_QUOTES);

	// check if Global Config `mailfrom` and `fromname` values exist
	if ($mosConfig_mailfrom != '' && $mosConfig_fromname != '') {
		$adminName2 = $mosConfig_fromname;
		$adminEmail2 = $mosConfig_mailfrom;
	} else {
	// use email address and name of first superadmin for use in email sent to user
		$query = "SELECT name, email"
		. "\n FROM #__users"
		. "\n WHERE LOWER( usertype ) = 'superadministrator'"
		. "\n OR LOWER( usertype ) = 'super administrator'"
		;
		$database->setQuery( $query );
		$rows = $database->loadObjectList();
		$row2 			= $rows[0];

		$adminName2 	= $row2->name;
		$adminEmail2 	= $row2->email;
	}

	// Send email to user
	mosMail($adminEmail2, $adminName2, $email, $subject, $message);

	// Send notification to all administrators
	$subject2 = sprintf (_SEND_SUB, $name, $mosConfig_sitename);
	$message2 = sprintf (ADMIN_EMAIL_REGISTRATION, $adminName2, $mosConfig_sitename, $row->id,$row->name, $email, $username);

	$msg_array=explode('(*extended details*)',$message2);
	$msg_array[0].="Extended Details\r\n";
	$query = "SELECT #__extending_field_list. *, #__extending_field_list.id as field_id, #__categories.title as cat_title"
		. "\n FROM #__extending_field_list"
		. "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
		. "\n ORDER by #__categories.ordering, #__extending_field_list.ordering";
	$database->setQuery( $query );
	$extended_fields = $database->loadObjectList();
	foreach($extended_fields as $field)
	{
		if($field -> published==1)
		{
			switch($field->type)
			{
				case 'select':
				case 'radio':
				case 'text':
				case 'textarea':
					$value=mosGetParam($_POST, 'extend'.$field->id);
					break;
				case 'checkbox':
					$value=mosGetParam($_POST, 'extend'.$field->id,'','array');
					$value=is_array($value)?implode("\r\n", $value) : $value='';
					break;
				case 'date':
					$data['d']=mosGetParam($_POST, 'extend_d'.$field->id);
          $data['m']=mosGetParam($_POST, 'extend_m'.$field->id);
          $data['y']=mosGetParam($_POST, 'extend_y'.$field->id);
					if(!$data['y'] || !$data['m'] || !$data['d']){
						$value='';
					}
					else{
						$value=is_array($data)?implode("-", $data) : $value='';
					}
					break;
        case 'file':
					$value=mosGetParam($_POST, 'extend'.$field->id, '');
					break;
        case 'phone':
          $phone['code']= mosGetParam($_POST, 'extend_code'.$field->id);
      		$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
      		$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
      		$phone['extention']=mosGetParam($_POST, 'extend_extention'.$field->id);
      		if(!$phone['code'] || !$phone['prefix'] || !$phone['phone']){
      			$value='';
      		}else{
      			$value=implode(' ',$phone);
      		}
          break;
        case 'simple phone':
      		$phone['prefix']=mosGetParam($_POST, 'extend_prefix'.$field->id);
      		$phone['phone']=mosGetParam($_POST, 'extend_phone'.$field->id);
      		if(!$phone['prefix'] || !$phone['phone']){
      			$value='';
      		}else{
      			$value=serialize($phone);
      		}
          break;
			}
			$msg_array[0].=$field->title.':  '.$value."\r\n";
		}
	}

	$message2=$msg_array[0].$msg_array[1];
	$subject2 = html_entity_decode($subject2, ENT_QUOTES);
	$message2 = html_entity_decode($message2, ENT_QUOTES);

	// get email addresses of all admins and superadmins set to recieve system emails
		$query = "SELECT email, sendEmail"
		. "\n FROM #__users"
	. "\n WHERE ( gid = 24 OR gid = 25 )"
	. "\n AND sendEmail = 1"
	. "\n AND block = 0"
		;
		$database->setQuery( $query );
	$admins = $database->loadObjectList();

	foreach ( $admins as $admin ) {
		// send email to admin & super admin set to recieve system emails
		mosMail($adminEmail2, $adminName2, $admin->email, $subject2, $message2);
	}
	if(JEConfig::get('general.activationuser_manual')){
	  echo sprintf(JUSER_REG_COMPLETE,$adminEmail2);
	}
	else{
  	if ( $mosConfig_useractivation == 1 ){
  		echo _REG_COMPLETE_ACTIVATE;
  	} else {
  		echo _REG_COMPLETE;
  	}
	}
	return true;
}

function userEdit( $option, $uid, $submitvalue) {
	global $database, $mainframe;
	global $mosConfig_absolute_path;

	// security check to see if link exists in a menu
	$link = 'index.php?option=com_juser&task=UserDetails';
	$query = "SELECT id"
	. "\n FROM #__menu"
	. "\n WHERE link LIKE '%$link%'"
	. "\n AND published = 1"
	;
	$database->setQuery( $query );
	$exists = $database->loadResult();
	if ( !$exists ) {
		mosNotAuth();
		return;
	}

	require_once( $mosConfig_absolute_path .'/administrator/components/com_juser/juser.class.php' );

	if ($uid == 0) {
		mosNotAuth();
		return;
	}
	$row = new mosUser( $database );
	$row->load( (int)$uid );
	$row->orig_password = $row->password;

	$file 	= $mainframe->getPath( 'com_xml', 'com_users' );
	$params =& new mosUserParameters( $row->params, $file, 'component' );

	$query = "SELECT #__extending_field_list. * , ud.field_id, ud.user_id,ud.uvalue,ud.ctime,#__extending_field_list.id as field_id , #__categories.title as cat_title, #__categories.description as cat_description"
		. "\n FROM #__extending_field_list"
		. "\n LEFT JOIN #__categories ON #__categories.id = #__extending_field_list.catid"
		. "\n LEFT JOIN #__users_extended_data  as ud ON #__extending_field_list.id = ud.field_id"
		. "\n AND ud.user_id = " . (int) $row->id
		. "\n ORDER by #__categories.ordering, #__extending_field_list.ordering";

	$database->setQuery( $query );
	$ext_row = $database->loadObjectList();

	HTML_JUser::userEdit( $row, $option, $params, $ext_row, 'saveUserEdit' );
}

function userSave( $option, $uid, $task) {
	global $database, $my, $mosConfig_frontend_userparams;

	$user_id = intval( mosGetParam( $_POST, 'id', 0 ));

	// do some security checks
	if ($uid == 0 || $user_id == 0 || $user_id != $uid) {
		mosNotAuth();
		return;
	}

	JUser::saveUser_ext($user_id);

	// simple spoof check security
//	josSpoofCheck();

	$row = new mosUser( $database );
	$row->load( (int)$user_id );

	$orig_password = $row->password;
	$orig_username = $row->username;

	if (!$row->bind( $_POST, 'gid usertype' )) {
		userRegistrationAfterError("com_juser", $my->id, array(), $row->getError(), $task);
		return false;
	}

	mosMakeHtmlSafe($row);

	if (isset($_POST['password']) && $_POST['password'] != '') {
		if (isset($_POST['verifyPass']) && ($_POST['verifyPass'] == $_POST['password'])) {
			$row->password = md5( $row->password );
		} else {
			userRegistrationAfterError("com_juser", $my->id, array(), _PASS_MATCH, $task);
			return false;
		}
	} else {
		// Restore 'original password'
		$row->password = $orig_password;
	}

	if ($mosConfig_frontend_userparams == '1' || $mosConfig_frontend_userparams == 1 || $mosConfig_frontend_userparams == NULL) {
	// save params
	$params = mosGetParam( $_POST, 'params', '' );
	if (is_array( $params )) {
		$txt = array();
		foreach ( $params as $k=>$v) {
			$txt[] = "$k=$v";
		}
		$row->params = @implode( "\n", $txt );
	}
	}

	if (!$row->check()) {
		userRegistrationAfterError("com_juser", $my->id, array(), $row->getError(), $task);
		return false;
	}

	if (!$row->store()) {
		userRegistrationAfterError("com_juser", $my->id, array(), $row->getError(), $task);
		return false;
	}

	// check if username has been changed
	if ( $orig_username != $row->username ) {
		// change username value in session table
		$query = "UPDATE #__session"
		. "\n SET username = '$row->username'"
		. "\n WHERE username = '$orig_username'"
		. "\n AND userid = $my->id"
		. "\n AND gid = $my->gid"
		. "\n AND guest = 0"
		;
		$database->setQuery( $query );
		$database->query();
	}
}

function CheckIn( $userid, $access, $option ){
	global $database;
	global $mosConfig_db;

	$nullDate = $database->getNullDate();
	if (!($access->canEdit || $access->canEditOwn || $userid > 0)) {
		mosNotAuth();
		return;
	}

	// security check to see if link exists in a menu
	$link = 'index.php?option=com_juser&task=CheckIn';
	$query = "SELECT id"
	. "\n FROM #__menu"
	. "\n WHERE link LIKE '%$link%'"
	. "\n AND published = 1"
	;
	$database->setQuery( $query );
	$exists = $database->loadResult();
	if ( !$exists ) {
		mosNotAuth();
		return;
	}

	$lt = mysql_list_tables($mosConfig_db);
	$k = 0;
	echo "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\">";
	while (list($tn) = mysql_fetch_array($lt)) {
		// only check in the jos_* tables
		if (strpos( $tn, $database->_table_prefix ) !== 0) {
			continue;
		}
		$lf = mysql_list_fields($mosConfig_db, "$tn");
		$nf = mysql_num_fields($lf);

		$checked_out = false;
		$editor = false;

		for ($i = 0; $i < $nf; $i++) {
			$fname = mysql_field_name($lf, $i);
			if ( $fname == "checked_out") {
				$checked_out = true;
			} else if ( $fname == "editor") {
				$editor = true;
			}
		}

		if ($checked_out) {
			if ($editor) {
				$query = "SELECT checked_out, editor"
				. "\n FROM $tn"
				. "\n WHERE checked_out > 0"
				. "\n AND checked_out = $userid"
				;
				$database->setQuery( $query );
			} else {
				$query = "SELECT checked_out"
				. "\n FROM $tn"
				. "\n WHERE checked_out > 0"
				. "\n AND checked_out = $userid"
				;
				$database->setQuery( $query );
			}
			$res = $database->query();
			$num = $database->getNumRows( $res );

			if ($editor) {
				$query = "UPDATE $tn"
				. "\n SET checked_out = 0, checked_out_time = '$nullDate', editor = NULL"
				. "\n WHERE checked_out > 0"
				;
				$database->setQuery( $query );
			} else {
				$query = "UPDATE $tn"
				. "\n SET checked_out = 0, checked_out_time = '$nullDate'"
				. "\n WHERE checked_out > 0"
				;
				$database->setQuery( $query );
			}
			$res = $database->query();

			if ($res == 1) {

				if ($num > 0) {
					echo "\n<tr class=\"row$k\">";
					echo "\n	<td width=\"250\">";
					echo _CHECK_TABLE;
					echo " - $tn</td>";
					echo "\n	<td>";
					echo _CHECKED_IN;
					echo "<b>$num</b>";
					echo _CHECKED_IN_ITEMS;
					echo "</td>";
					echo "\n</tr>";
				}
				$k = 1 - $k;
			}
		}
	}
	?>
	<tr>
		<td colspan="2">
			<b><?php echo _CONF_CHECKED_IN; ?></b>
		</td>
	</tr>
	</table>
	<?php
}
?>
